﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DelegateDemo3
{
    //定义委托
    public delegate string GeneralEventHandler();

    //定义事件发布者
    public class Publisher
    {
        //声明一个委托变量
        private GeneralEventHandler numberChanged;
        //事件访问器的定义
        public event GeneralEventHandler NumberChanged
        {
            add
            {
                numberChanged = value;
            }
            remove
            {
                numberChanged -= value;
            }
        }

        public void DoSomething()
        {
            if (numberChanged != null)
            {
                string rtn = numberChanged();
                Console.WriteLine("Return:{0}", rtn);
            }
        }
    }

    //定义事件订阅者
    public class Subscriber1
    {
        public string OnNumberChanged()
        {
            Console.WriteLine("Subscriber1 Invoked!");
            return "Subscriber1";
        }
    }
    public class Subscriber2
    {
        public string OnNumberChanged()
        {
            Console.WriteLine("Subscriber2 Invoked!");
            return "Subscriber2";
        }
    }
    public class Subscriber3
    {
        public string OnNumberChanged()
        {
            Console.WriteLine("Subscriber3 Invoked!");
            return "Subscriber3";
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Publisher pub = new Publisher();
            Subscriber1 sub1 = new Subscriber1();
            Subscriber2 sub2 = new Subscriber2();
            Subscriber3 sub3 = new Subscriber3();

            pub.NumberChanged -= sub1.OnNumberChanged;
            pub.NumberChanged += sub2.OnNumberChanged;
            pub.NumberChanged += sub1.OnNumberChanged;
            //得到的输出是Subscriber3，只得到了最后一个方法的返回值
            pub.DoSomething();
        }
    }
}
